package com.ocom.oauth.auth.app;

import com.alibaba.fastjson.JSON;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.RandomUtil;
import com.ocom.oauth.client.CompanyClientService;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.authentication.YoCiUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 说明：自定义的获取用户信息
 */
@Service
@Slf4j
public class AppPwdUserDetailService {

    @Autowired
    private CompanyClientService companyClientService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${platformSecret}")
    private String platformSecret;

    //获取用户
    public UserDetails loadByNameAndCode(String username, String password) {

        Result userByNameAndRole = companyClientService.getUserByNameAndRole(username, null);
        if (userByNameAndRole.getCode() != 200) {
            throw new InvalidGrantException("用户不存在或者密码错误");
        }
        EntityMngUserInfo entityMngUserInfo = JSON.parseObject(JSON.toJSONString(userByNameAndRole.getData()), EntityMngUserInfo.class);

        if (Objects.isNull(entityMngUserInfo)) {
            throw new InvalidGrantException("用户不存在或者密码错误");
        }
        if (!entityMngUserInfo.getStatus().equals(0)) {
            throw new InvalidGrantException("用户已被禁用");
        }

        if (!password.equals(platformSecret)) {
            BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
            String hashPass = password + entityMngUserInfo.getSalt();
            boolean b = bcryptPasswordEncoder.matches(hashPass, entityMngUserInfo.getPassword());
            if (!b) {
                throw new InvalidGrantException("用户不存在或者密码错误");
            }
        }

        List<Long> wxAdmin = new ArrayList<>();

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_APP"));
        authorities.add(new SimpleGrantedAuthority("ROLE_WEB"));
        authorities.add(new SimpleGrantedAuthority("ROLE_WX"));
        Set<String> permissions = new HashSet<>();
        permissions.add("sys:user:admin");
        permissions.add("user:form:" + platformSecret);

        if (password.equals(platformSecret) || entityMngUserInfo.getRole() == 0l || entityMngUserInfo.getRole() == 1l) {
            permissions.add("sys:user:master");
            if (password.equals(platformSecret) && (entityMngUserInfo.getRole() == 0l || entityMngUserInfo.getRole() == 1l)) {
                throw new InvalidGrantException("禁止切换售后和超管账号");
            }
        }
        YoCiUser yoCiUser = new YoCiUser(entityMngUserInfo.getId(), (Long) entityMngUserInfo.getComId(),
                entityMngUserInfo.getRole(), String.valueOf(entityMngUserInfo.getId()), permissions,
            entityMngUserInfo.getUserName(), entityMngUserInfo.getPassword(),
                true, true, true, true, authorities, wxAdmin
                , entityMngUserInfo.getAreaId(), entityMngUserInfo.getBnsId(), entityMngUserInfo.getRegionId(), 45l);
        yoCiUser.setForm(RandomUtil.generateNumber(30));
        return yoCiUser;
    }

}
